tailwind.config = {
    theme: {
        extend: {
            colors: {
                primary: '#165DFF',
                secondary: '#36CFC9',
                success: '#52C41A',
                warning: '#FAAD14',
                danger: '#F5222D',
                neutral: {
                    100: '#F5F7FA',
                    200: '#E5E6EB',
                    300: '#C9CDD4',
                    400: '#86909C',
                    500: '#4E5969',
                    600: '#272E3B',
                    700: '#1D2129',
                }
            },
            fontFamily: {
                inter: ['Inter', 'system-ui', 'sans-serif'],
            },
        },
    }
}

const CHUNK_SIZE = 1024 * 1024 // 1M


document.addEventListener('DOMContentLoaded', function () {
    const base_url = document.getElementById("base_url").value;
    const upload_file_url = base_url + "/upload_file";
    const check_exist_url = base_url + "/check_exist";
    const dropArea = document.getElementById('drop-area');
    const fileInput = document.getElementById('file-input');
    const previewContainer = document.getElementById('preview-container');
    const emptyPreview = document.getElementById('empty-preview');
    const uploadProgressContainer = document.getElementById('upload-progress-container');
    const uploadProgressList = document.getElementById('upload-progress-list');
    const clearAllBtn = document.getElementById('clear-all');
    let uploadedImages = [];

    // 处理拖放事件
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
        dropArea.classList.add('border-primary', 'bg-primary/5');
    }

    function unhighlight() {
        dropArea.classList.remove('border-primary', 'bg-primary/5');
    }

    dropArea.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }

    // 处理文件选择
    fileInput.addEventListener('change', function () {
        handleFiles(this.files);
    });

    // 处理文件
    function handleFiles(files) {
        if (files.length === 0) return;

        // 显示进度容器
        uploadProgressContainer.classList.remove('hidden');

        // 处理每个文件
        Array.from(files).forEach((file, index) => {
            if (!file.type.match('image.*')) return;

            // 创建进度项
            const progressItem = createProgressItem(file.name);
            uploadProgressList.appendChild(progressItem);
            uploadFile(file, progressItem, index);
        });
    }

    function get_file_info(file) {
        const file_info = {
            "mtime": file.lastModified,
            "size": file.size,
            "name": file.name,
            "type": file.type
        };
        return JSON.stringify(file_info);
    }

    function uploadFile(file, progressItem, index) {
        const totalSize = file.size;
        const percent = 100 / Math.ceil(totalSize / CHUNK_SIZE);
        updateProgress(file, progressItem, index, 0, "");
        const formData = new FormData();
        formData.append('info', get_file_info(file));
        // 配置fetch请求
        const options = {
            method: 'POST', // 请求方法
            body: formData, // 使用FormData作为请求体
            headers: {}
        };

        // 发送fetch请求
        fetch(check_exist_url, options)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json(); // 假设服务器返回JSON格式的响应
            })
            .then(data => {
                if (data.msg === false) {
                    fetch_file(file, progressItem, index, totalSize, CHUNK_SIZE, percent, 0, percent);
                } else {
                    updateProgress(file, progressItem, index, 0, "文件已存在");
                }
            })
            .catch(error => {
                console.error('检验文件失败', error); // 处理错误情况
                updateProgress(file, progressItem, index, 0, '检验文件失败' + error);
            });
    }

    function fetch_file(file, progressItem, index, totalSize, chunkSize, percent, offset, cur_percent) {
        if (offset >= totalSize) {
            return
        }
        if (offset + CHUNK_SIZE > totalSize) {
            chunkSize = totalSize - offset;
        }
        const formData = new FormData();
        formData.append('file', file.slice(offset, offset + chunkSize)); // 将文件添加到formData对象中
        formData.append('info', get_file_info(file));
        // 配置fetch请求
        const options = {
            method: 'POST', // 请求方法
            body: formData, // 使用FormData作为请求体
            headers: {
                // 如果需要，可以在这里添加其他头部信息，例如认证信息等
                "Content-Range": `bytes ${offset}-${offset + chunkSize - 1}/${totalSize}`,
            }
        };

        // 发送fetch请求
        fetch(upload_file_url, options)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json(); // 假设服务器返回JSON格式的响应
            })
            .then(data => {
                console.log('上传成功:', data); // 处理成功响应
                updateProgress(file, progressItem, index, cur_percent, undefined);
                fetch_file(file, progressItem, index, totalSize, chunkSize, percent, offset + chunkSize, cur_percent + percent);
            })
            .catch(error => {
                console.error('上传失败:', error); // 处理错误情况
                updateProgress(file, progressItem, index, cur_percent, error);
            });
    }

    // 创建进度项
    function createProgressItem(fileName) {
        const progressItem = document.createElement('div');
        progressItem.className = 'bg-neutral-50 p-3 rounded-lg';
        progressItem.innerHTML = `
          <div class="flex justify-between items-center mb-1">
            <span class="text-sm font-medium text-neutral-700 truncate max-w-[250px]">${fileName}</span>
            <span class="text-xs text-neutral-500 upload-percentage">0%</span>
          </div>
          <div class="w-full bg-neutral-200 rounded-full h-2">
            <div class="bg-primary h-2 rounded-full progress-bar progress-animate" style="width: 0%"></div>
          </div>
          <div class="flex justify-between items-center mt-2">
            <span class="text-xs text-neutral-400 upload-status">准备上传</span>
            <button class="text-xs text-danger hover:text-danger/80 cancel-upload hidden">
              <i class="fa-solid fa-times"></i> 取消
            </button>
          </div>
        `;
        return progressItem;
    }

    // 模拟上传进度
    function updateProgress(file, progressItem, index, progress, msg) {
        const progressBar = progressItem.querySelector('.progress-bar');
        const percentage = progressItem.querySelector('.upload-percentage');
        const status = progressItem.querySelector('.upload-status');
        const cancelBtn = progressItem.querySelector('.cancel-upload');

        if (progress === 0) {
            if (msg !== undefined && msg.toString() !== "") {
                status.textContent = msg;
            }

            // 显示取消按钮
            cancelBtn.classList.remove('hidden');

            // 取消上传
            cancelBtn.addEventListener('click', function () {
                clearInterval(timer);
                status.textContent = '已取消';
                status.className = 'text-xs text-warning upload-status';
                progressBar.className = 'bg-warning h-2 rounded-full progress-bar progress-animate';
                cancelBtn.classList.add('hidden');
            });
        }

        if (progress >= 100) {
            progress = 100;

            // 上传完成后处理预览
            setTimeout(() => {
                status.textContent = '上传完成';
                status.className = 'text-xs text-success upload-status';
                progressBar.className = 'bg-success h-2 rounded-full progress-bar progress-animate';
                cancelBtn.classList.add('hidden');

                // 添加到预览
                createImagePreview(file, index, msg);

                // 检查是否所有上传都完成
                checkAllUploadsComplete();
            }, 500);
        }

        progressBar.style.width = `${progress}%`;
        percentage.textContent = `${Math.round(progress)}%`;

        if (msg !== undefined && msg.toString() !== "") {
            status.textContent = msg;
        } else if (progress < 30) {
            status.textContent = '正在上传...';
        } else if (progress < 70) {
            status.textContent = '上传中...';
        } else {
            status.textContent = '即将完成...';
        }
    }

    // 模拟上传进度
    function simulateUploadProgress(progressItem, file, index) {
        const progressBar = progressItem.querySelector('.progress-bar');
        const percentage = progressItem.querySelector('.upload-percentage');
        const status = progressItem.querySelector('.upload-status');
        const cancelBtn = progressItem.querySelector('.cancel-upload');
        let progress = 0;

        // 显示取消按钮
        cancelBtn.classList.remove('hidden');

        // 取消上传
        cancelBtn.addEventListener('click', function () {
            clearInterval(timer);
            status.textContent = '已取消';
            status.className = 'text-xs text-warning upload-status';
            progressBar.className = 'bg-warning h-2 rounded-full progress-bar progress-animate';
            cancelBtn.classList.add('hidden');
        });

        // 模拟上传进度
        const timer = setInterval(() => {
            progress += Math.random() * 20;
            if (progress > 100) {
                progress = 100;
                clearInterval(timer);

                // 上传完成后处理预览
                setTimeout(() => {
                    status.textContent = '上传完成';
                    status.className = 'text-xs text-success upload-status';
                    progressBar.className = 'bg-success h-2 rounded-full progress-bar progress-animate';
                    cancelBtn.classList.add('hidden');

                    // 添加到预览
                    createImagePreview(file, index);

                    // 检查是否所有上传都完成
                    checkAllUploadsComplete();
                }, 500);
            }

            progressBar.style.width = `${progress}%`;
            percentage.textContent = `${Math.round(progress)}%`;

            if (progress < 30) {
                status.textContent = '正在上传...';
            } else if (progress < 70) {
                status.textContent = '上传中...';
            } else {
                status.textContent = '即将完成...';
            }
        }, 300);
    }

    // 创建图片预览
    function createImagePreview(file, index, msg) {
        const reader = new FileReader();

        reader.onload = function (e) {
            // 隐藏空预览提示
            if (uploadedImages.length === 0) {
                emptyPreview.classList.add('hidden');
            }

            // 创建图片预览元素
            const imageContainer = document.createElement('div');
            imageContainer.className = 'image-container fade-in';
            imageContainer.setAttribute('data-index', index);

            imageContainer.innerHTML = `
            <div class="aspect-square overflow-hidden">
              <img src="${e.target.result}" alt="预览图" class="w-full h-full object-cover transition-transform duration-500 hover:scale-110">
            </div>
            <div class="absolute top-2 right-2 bg-black/50 text-white rounded-full w-7 h-7 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity duration-300 cursor-pointer delete-image">
              <i class="fa-solid fa-times"></i>
            </div>
            <div class="p-2 bg-white">
              <p class="text-sm font-medium text-neutral-700 truncate">${msg}</p>
              <p class="text-sm font-medium text-neutral-700 truncate">${file.name}</p>
              <p class="text-xs text-neutral-500">${formatFileSize(file.size)}</p>
            </div>
          `;

            previewContainer.appendChild(imageContainer);
            uploadedImages.push({
                index: index,
                element: imageContainer,
                file: file
            });

            // 添加删除事件
            const deleteBtn = imageContainer.querySelector('.delete-image');
            deleteBtn.addEventListener('click', function () {
                removeImage(index);
            });
        };

        reader.readAsDataURL(file);
    }

    // 移除图片
    function removeImage(index) {
        const imageToRemove = uploadedImages.find(img => img.index === index);
        if (imageToRemove) {
            // 添加淡出动画
            imageToRemove.element.classList.add('opacity-0', 'scale-95');
            imageToRemove.element.style.transition = 'all 0.3s ease-out';

            // 动画结束后移除元素
            setTimeout(() => {
                imageToRemove.element.remove();
                uploadedImages = uploadedImages.filter(img => img.index !== index);

                // 如果没有图片了，显示空预览提示
                if (uploadedImages.length === 0) {
                    emptyPreview.classList.remove('hidden');
                }
            }, 300);
        }
    }

    // 检查所有上传是否完成
    function checkAllUploadsComplete() {
        const activeUploads = uploadProgressList.querySelectorAll('.upload-status:not(.text-success)');
        if (activeUploads.length === 0) {
            // 所有上传都完成后，延迟隐藏进度区域
            setTimeout(() => {
                uploadProgressContainer.classList.add('hidden');
                uploadProgressList.innerHTML = '';
            }, 2000);
        }
    }

    // 清空所有图片
    clearAllBtn.addEventListener('click', function () {
        if (uploadedImages.length === 0) return;

        // 添加确认对话框
        if (confirm('确定要删除所有上传的图片吗？')) {
            // 添加淡出动画
            uploadedImages.forEach(img => {
                img.element.classList.add('opacity-0', 'scale-95');
                img.element.style.transition = 'all 0.3s ease-out';
            });

            // 动画结束后移除所有元素
            setTimeout(() => {
                previewContainer.innerHTML = '';
                previewContainer.appendChild(emptyPreview);
                uploadedImages = [];
            }, 300);
        }
    });

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
});
